#!/usr/bin/python
# -*- coding: utf-8 -*-

'''
参考: http://packages.python.org/PySQLPool/tutorial.html
'''

__author__ = 'lyj'


import PySQLPool

# Getting Started
connection = PySQLPool.getNewConnection(username='root', password='', host='localhost', db='test')
query = PySQLPool.getNewQuery(connection)

# Selecting Data
query.Query('select * from table')
for row in query.record:
    print row['column']

# Updating Data
query.Query('update table set column = 1')
print 'Affected Rows:', query.affectedRows

# Inserting New Data
query.Query("insert into table (`column`) values ('1')")
print 'Last Insert ID:', query.lastInsertID

# Using PySQLPool with Threads
import threading

class MyThread(threading.thread):
    def __init__(self):
            ...

    def run(self):
        query = PySQLPool.getNewQuery(connection)
        query.Query("insert into table (`column`) values ('1')")


# Setting the Max Connection Limit
PySQLPool.getNewPool().maxActiveConnections = 1


# Stream Selected Data
# 针对大数据集，QueryOne不会将结果全部放入内存，而是通过流的形式一行一行返回
query.QueryOne('select * from table')
for row in query.record:
    print row['column']

# 处理异常
import sys
import MySQLdb
try:
    connection = PySQLPool.getNewConnection(username='root', password='123456', host='localhost', db='mydb')
    query = PySQLPool.getNewQuery(connection)
    query.Query('select * from table')
except MySQLdb.Error, e:
    print "Error %d: %s" % (e.args[0], e.args[1])
    sys.exit (1)

# 本地调试
PySQLPool.PySQLQuery.logging_path = '/path/to/file.txt'


if __name__ == '__main__':
    pass  